package top.canyue.eca_manager.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.canyue.eca_manager.bean.OperationLog;
import top.canyue.eca_manager.bean.Result;
import top.canyue.eca_manager.mapper.OperationLogMapper;
import top.canyue.eca_manager.service.LogService;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 日志功能统一整合在这
 *
 * @author Canyue 2024-05-10
 */

@Service
public class LogServiceImpl implements LogService {
    @Autowired
    private OperationLogMapper operationLogMapper;

    private Map<String, Long> fullTrendDataByWeek(List<Map<String, Object>> oraginData) {
        Map<LocalDate, Long> dateCountMap = oraginData.stream()
                .collect(Collectors.toMap(
                        node -> LocalDate.parse(node.get("date").toString()),
                        node -> (Long) node.get("count"),
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                ));

        LocalDate startDate = LocalDate.now().plusDays(-6);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return IntStream.range(0, 7)
                .mapToObj(startDate::plusDays)
                .collect(Collectors.toMap(
                        date -> date.format(dtf),
                        date -> dateCountMap.getOrDefault(date, 0L),
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                ));
    }

    @Override
    public boolean record(String userId, String level, String operation, String params, Integer resultStatic) {
        if (level.isEmpty() || operation.isEmpty() || resultStatic == null) return false;
        OperationLog operationLog = new OperationLog(userId, level, operation, params, resultStatic);
        return operationLogMapper.record(operationLog) == 1;
    }

    @Override
    public Result getLoginTrendByWeek() {
        Result result = new Result();
        result.setStatus(200);
        result.setMsg("OK");
        List<Map<String, Object>> oraginData = operationLogMapper.getLoginTrendByWeek();
        result.setData(fullTrendDataByWeek(oraginData));
        return result;
    }

    @Override
    public Result getSystemStability() {
        Result result = new Result();
        List<Map<String, Object>> systemStability = operationLogMapper.getSystemStability();
        result.setStatus(200);
        result.setMsg("OK");
        result.setData(systemStability);
        return result;
    }


}
